//
//  JYJNetWorkParser.m
//  HappyListen
//
//  Created by 冀永金 on 16/8/17.
//  Copyright © 2016年 冀永金. All rights reserved.
//

#import "JYJNetWorkParser.h"
#import "AFNetworking.h"

@implementation JYJNetWorkParser
+(void)GET:(NSString *)url
   andBody:(id)body
 andHeader:(NSDictionary *)headers
andResponse:(JYJResponseStyle)responseStyle
andSuccessBlock:(successBlock)success
andFailureBlock:(failureBlock)failure
{
    
    // 1. 设置网络管理者
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    // 2. 设置请求头
    
    if (headers) {
        
        for (NSString *key in headers.allKeys) {
            
            [manager.requestSerializer setValue:headers[key] forHTTPHeaderField:key];
            
        }
    }
    
    // 3. 设置返回数据的类型
    switch (responseStyle) {
        case JYJJSON:
            manager.responseSerializer = [AFJSONResponseSerializer serializer];
            break;
        case JYJXML:
            manager.responseSerializer = [AFXMLParserResponseSerializer serializer];
            break;
        case JYJDATA:
            manager.responseSerializer = [AFHTTPResponseSerializer serializer];
            break;
            
        default:
            break;
    }
    
    // 4. 设置响应数据类型
    
    [manager.responseSerializer setAcceptableContentTypes:[NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/css",@"text/plain", @"application/javascript",@"image/jpeg", @"text/vnd.wap.wml", @"text/xml", @"application/x-javascript", nil]];
    
    
    // 5. UTF-8转码
    
    url = [url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    
    
    // 6. 使用AFN进行网络请求
    
    [manager GET:url parameters:body progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        if (responseObject) {
            success(responseObject);
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        if (error) {
            failure(error);
        }
        
    }];
}


+(void)POST:(NSString *)url andBody:(id)body andBodyStyle:(JYJRequestStyle)bodyStyle andHeader:(NSDictionary *)headers andResponse:(JYJResponseStyle)responseStyle andSuccessBlock:(successBlock)success andFailureBlock:(failureBlock)failure
{
    
    AFNetworkReachabilityManager *netWorkManager = [AFNetworkReachabilityManager sharedManager];
    [[AFNetworkReachabilityManager sharedManager] startMonitoring];
    NSString *documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSLog(@"%@", documentPath);
    
    // 文件管理器
    NSFileManager *Filemanager = [NSFileManager defaultManager];
    NSString *musicCaches = [documentPath stringByAppendingPathComponent:@"musicCaches"];
    BOOL resultFile =  [Filemanager createDirectoryAtPath:musicCaches withIntermediateDirectories:YES attributes:nil error:nil];
    if (resultFile) {
        NSLog(@"创建缓存文件夹成功");
    }
    // 拼接缓存路径
    NSString *path = [NSString stringWithFormat:@"%ld.plist", (unsigned long)[url hash]];
    NSString *textFilePath = [musicCaches stringByAppendingPathComponent:path];
    
    
    // 检测网络连接的单例,网络变化时回调方法
    [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        NSLog(@"网络状态 = %ld", status);
    }];

    // 1. 设置网络管理者
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    
    // 2. 设置body的数据类型
    
    switch (bodyStyle) {
        case JYJBodyJSON:
            
            manager.requestSerializer = [AFJSONRequestSerializer serializer];
            
            break;
            
        case JYJBodyString:
            
            [manager.requestSerializer setQueryStringSerializationWithBlock:^NSString * _Nonnull(NSURLRequest * _Nonnull request, id  _Nonnull parameters, NSError * _Nullable * _Nullable error) {
                
                return parameters;
                
            }];
            
            break;
            
        default:
            break;
    }
    
    // 3. 设置请求头
    
    if (headers) {
        
        for (NSString *key in headers.allKeys) {
            
            [manager.requestSerializer setValue:headers[key] forHTTPHeaderField:key];
            
        }
    }
    
    // 3. 设置返回数据的类型
    switch (responseStyle) {
        case JYJJSON:
            manager.responseSerializer = [AFJSONResponseSerializer serializer];
            break;
        case JYJXML:
            manager.responseSerializer = [AFXMLParserResponseSerializer serializer];
            break;
        case JYJDATA:
            manager.responseSerializer = [AFHTTPResponseSerializer serializer];
            break;
            
        default:
            break;
    }
    
    // 4. 设置响应数据类型
    
    [manager.responseSerializer setAcceptableContentTypes:[NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/css",@"text/plain", @"application/javascript",@"image/jpeg", @"text/vnd.wap.wml", @"application/x-javascript", nil]];
    
    
    // 5. UTF-8转码
    
    url = [url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    
    
    // 6. 使用AFN进行网络请求
    
    [manager POST:url parameters:body progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        [netWorkManager stopMonitoring];
        
        //请求成功归档储存请求的数据.
        BOOL result   = [NSKeyedArchiver archiveRootObject:responseObject toFile:textFilePath];
        
        //        BOOL result = [data writeToFile:textFilePath atomically:YES encoding:NSUTF8StringEncoding error:nil];
        //        BOOL result = [responseObject writeToURL:[NSURL URLWithString:textFilePath] atomically:YES encoding:NSUTF8StringEncoding error:nil];
        
        if (result) {
            NSLog(@"写入文件成功");
        }

        
        success(responseObject);
       
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        //请求失败(没有网),从本地文件夹获取数据
        id result = [NSKeyedUnarchiver unarchiveObjectWithFile:textFilePath];
        
        if (result) {
            
            NSLog(@"网络加载失败,从本地获取数据");
        }
        

        
            failure(error);
        success(result);
        
    }];
    
}

@end
